package tree.迭代bfs;

import tree.Node;

import java.util.*;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName IM多叉树的前序遍历589.java
 * @Description https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
 * @createTime 2021年06月17日 19:21:00
 */
public class IM多叉树的前序遍历589 {

    List<Integer> list = new ArrayList<>();

    /*
    递归方案
    public List<Integer> preorder(Node root) {
        if (root == null) {
            return list;
        }
        listNode(root);
        return list;
    }

    private void listNode(Node node) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        for (Node child : node.children) {
            listNode(child);
        }
    }*/

    public List<Integer> preorder(Node root) {
        if (root == null) {
            return list;
        }
        Deque<Node> deque = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            //todo 放在最后
            Node node = deque.pollLast();
            list.add(node.val);
            if (node.children != null) {
                List<Node> children = node.children;
                //todo 翻转
                Collections.reverse(children);
                for (Node child : children) {
                    deque.offer(child);
                }
            }
        }
        return list;
    }

}

;